# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：category的curd
"""
from fastapi import HTTPException
from schemas.category import CategoryAddSchemas, CategoryOutSchemas, CategoryEditSchemas
from models.base import Category


async def category_add_curd(post: CategoryAddSchemas) -> CategoryOutSchemas:
    if await Category.get_or_none(name=post.name):
        raise HTTPException(status_code=422, detail='分类名称不能重复!')
    if post.pid:
        if post.level == 1:
            raise HTTPException(status_code=422, detail='存在父级id时level不可能为1级!')
        if not await Category.get_or_none(id=post.pid):
            raise HTTPException(status_code=422, detail='父级id不存在!')
    category = await Category.create(name=post.name, level=post.level, pid_id=post.pid)
    return CategoryOutSchemas(**dict(category))


async def category_edit_curd(post: CategoryEditSchemas) -> CategoryOutSchemas:
    category = await Category.get_or_none(id=post.id)
    if not await category:
        raise HTTPException(status_code=422, detail='该商品分类不存在！')
    if post.pid_id:
        if post.level == 1:
            raise HTTPException(status_code=422, detail='存在父级id时level不可能为1级!')
        if not await Category.get_or_none(id=post.pid_id):
            raise HTTPException(status_code=422, detail='父级id不存在!')

    await category.update_from_dict(post.dict())
    await category.save()
    return CategoryOutSchemas(**dict(category))
